/**
 * 给与目标房间视野
 */

let baser = require("./baser");

/**
 * 
 * @param {[roomname]} roomnames 
 * @returns 
 */
module.exports = function (roomnames) {
    return baser(
        /**
         * 准备函数，获取房间下标
         * @param {Creep} creep
         */
        function (creep) {
            if (!creep.id) {
                return 1;
            }
            if (creep.memory.g_patrol_index) {
                return 2;
            }
            if (!Game.rooms[creep.memory.roomname].memory.g_patrol_id) {
                Game.rooms[creep.memory.roomname].memory.g_patrol_id = [];
            }
            for (let i in roomnames) {
                // 该位置没有creep
                if (!Game.getObjectById(Game.rooms[creep.memory.roomname].memory.g_patrol_id[i]) ||
                    Game.getObjectById(Game.rooms[creep.memory.roomname].memory.g_patrol_id[i]) == creep) {
                    Game.rooms[creep.memory.roomname].memory.g_patrol_id[i] = creep.id;
                    creep.memory.g_patrol_index = i;
                    return 2;
                }
            }
            return 1;
        },
        /**
         * 工作函数，去往房间
         * @param {Creep} creep
         */
        function (creep) {
            if (!creep.memory.g_patrol_index) return 1;
            let roomname = roomnames[creep.memory.g_patrol_index];
            // 到达房间
            if (creep.room.name == roomname) {
                if (creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS)) {
                    return 3;
                }
                creep.move(1 + parseInt(Math.random() * 7.99));
                return 2;
            }
            // 去往房间
            creep.actionToRoom(roomname);
            return 2;
        },
        /**
         * 
         * @param {Creep} creep
         */
        function (creep) {
            if (!creep.memory.g_patrol_index) return 1;
            let roomname = roomnames[creep.memory.g_patrol_index];
            // 不在目标房间
            if (creep.room.name != roomname) {
                creep.moveTo(creep.room.controller);
                return 2;
            }
            // 离开目标房间
            creep.actionToRoom(creep.memory.roomname);
            return 3;
        });
}
